from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv
from whiff.middleware import setInnerHtml
#import pprint # for debug
from whiff.rdjson import jsonParse
import infoSchema

class flattenSchemaCallback(misc.utility):
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        cgiDict = env[whiffenv.CGI_DICTIONARY]
        dataString = whiffenv.cgiGet(env, "schema", "{}").strip()
        dataString = resolver.unquote(dataString)
        schemaData = self.param_json(dataString, env)
        # flatten the schema data
        S = infoSchema.schemaFromJsonValue(schemaData)
        newS = S.flatten()
        schemaData = newS.jsonValue()
        # save and load the schema data
        schemaJson = jsonParse.format(schemaData)
        #pr "new json"
        #pr schemaJson
        target = "schemaData"
        application = setInnerHtml.__middleware__(page=schemaJson, elementName=target)
        setHtml = self.param_value(application, env)
        tailAction = DODRAW
        start_response("200 OK", [('Content-Type', 'application/javascript')])
        return [setHtml, tailAction]
    def getAttributeDescription(self, env, name):
        descr = {}
        newname = descr["name"] = whiffenv.cgiGet(env, "attributeName_"+name, "")
        newtypeName = descr["typeName"] = whiffenv.cgiGet(env, "attributeKind_"+name, "")
        descr["isIdentifier"] = (whiffenv.cgiGet(env, "attributeIsIdentifier_"+name, None) is not None)
        descr["isMandatory"] = (whiffenv.cgiGet(env, "attributeIsMandatory_"+name, None) is not None)
        descr["isOnto"] = (whiffenv.cgiGet(env, "attributeIsOnto_"+name, None) is not None)
        descr["isOneToOne"] = (whiffenv.cgiGet(env, "attributeIsOneToOne_"+name, None) is not None)
        descr["isMultiple"] = (whiffenv.cgiGet(env, "attributeIsMultiple_"+name, None) is not None)
        #pr name, "becomes", descr
        if newname and newtypeName:
            return descr
        else:
            return None

DODRAW = """
closePrompt();
//alert("now redrawing schema");
drawSchemaFromData();
"""

__middleware__ = flattenSchemaCallback
